// --------------------------------------------------------------------------------------------------------------------
// <copyright file="VelocityControlledJointPositionControllerTests.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Test.Robotics.Manipulation.JointController
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    using Microsoft.Robotics.Core.Algorithms;
    using Microsoft.Robotics.Manipulation;
    using Microsoft.Robotics.Manipulation.JointController;
    using Microsoft.Robotics.Numerics;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    /// <summary>
    /// Tests for VelocityControlledJointPositionControllerTests class
    /// </summary>
    [TestClass]
    public class VelocityControlledJointPositionControllerTests
    {
        /// <summary>
        /// Test constructor
        /// </summary>
        [TestMethod]
        [TestCategory("Unit")]
        [Priority(0)]
        public void VelocityControlledJointPositionControllerConstructorTest()
        {
            const int numJoints = 7;

            PidController[] pidControllers = new PidController[numJoints];
            double[] deadband = new double[] {0, 0, 0, 0, 0, 0, 0};
            double[] maxDelta = new double[] {1, 1, 1, 1, 1, 1, 1};
            double[] maxVelocity = new double[] {1, 1, 1, 1, 1, 1, 1};

            for (int i = 0; i < numJoints; ++i)
            {
                pidControllers[i] = new PidController(1, 0, 0, i, i * 2, i * 3, 1000);
            }

            VelocityControlledJointPositionController controller = new VelocityControlledJointPositionController(
                numJoints, 
                pidControllers, 
                deadband,
                maxDelta,
                maxVelocity);

            Assert.AreEqual(JointSignalType.Position, controller.ReferenceSignalType);
            Assert.AreEqual(JointSignalType.Velocity, controller.ControlOutputSignalType);
        }

        /// <summary>
        /// Test constructor with invalid parameters
        /// </summary>
        [TestMethod]
        [TestCategory("Unit")]
        [Priority(0)]
        [ExpectedException(typeof(ArgumentException))]
        public void VelocityControlledJointPositionControllerConstructorInvalidParametersTest()
        {
            const int numJoints = 7;

            // don't supply enough pid controllers
            PidController[] pidControllers = new PidController[numJoints - 1];
            double[] deadband = new double[] { 0, 0, 0, 0, 0, 0 };
            double[] maxDelta = new double[] { 1, 1, 1, 1, 1, 1 };
            double[] maxVelocity = new double[] { 1, 1, 1, 1, 1, 1 };
            for (int i = 0; i < numJoints - 1; ++i)
            {
                pidControllers[i] = new PidController(1, 0, 0, i, i * 2, i * 3, 1000);
            }

            VelocityControlledJointPositionController controller = new VelocityControlledJointPositionController(
                numJoints,
                pidControllers,
                deadband,
                maxDelta,
                maxVelocity);
        }

        /// <summary>
        /// Test functioning of controller
        /// </summary>
        [TestMethod]
        [TestCategory("Unit")]
        [Priority(0)]
        public void VelocityControlledJointPositionControllerCycleTest()
        {
            const int numJoints = 2;
            const int numIterations = 1000;
            const int cycleTimeInMS = 10;

            double[] currentPositions = new double[] { -1.0, 1.0 };

            PidController[] pidControllers = new PidController[numJoints];

            for (int i = 0; i < numJoints; ++i)
            {
                pidControllers[i] = new PidController(10, -10, 0, 7, 0, 0.7, 1000000);
            }

            double[] deadband = new double[] { 0, 0 };
            double[] maxDelta = new double[] { 1, 1 };
            double[] maxVelocity = new double[] { 1, 1 };

            VelocityControlledJointPositionController controller = new VelocityControlledJointPositionController(
               numJoints,
               pidControllers,
               deadband,
               maxDelta,
               maxVelocity);

            ManipulatorStatus status = this.BuildManipulatorStatusFromPosition(currentPositions, 0);
            for (int i = 0; i < numIterations; ++i)
            {
                double[] velocities = controller.Cycle(status);

                for (int j = 0; j < numJoints; ++j)
                {
                    currentPositions[j] += velocities[j] * cycleTimeInMS / 1000.0;
                }

                status = this.BuildManipulatorStatusFromPosition(currentPositions, i * 10);
            }

            for (int i = 0; i < numJoints; ++i)
            {
                Assert.AreEqual(0.0, currentPositions[i], MathConstants.ErrorEpsilon);
            }
        }

        /// <summary>
        /// Builds an instance of <see cref="ManipulatorStatus"/> with given values for joint
        /// positions, and zero/default values for all other fields.
        /// </summary>
        /// <param name="position">Joint positions.</param>
        /// <param name="timestamp">Timestamp in MS</param>
        /// <returns>Manipulator status</returns>
        private ManipulatorStatus BuildManipulatorStatusFromPosition(double[] position, double timestamp)
	{
            double[] zeroArray = new double[] { 0, 0 };
            return new ManipulatorStatus(
                timestamp,
                new Pose(),
                new Pose(),
                position,
                zeroArray,
                zeroArray,
                zeroArray,
                zeroArray,
                zeroArray);
	}
    }
}
